from PIL import Image
import openpyxl
from openpyxl.styles import Color
from openpyxl.utils import get_column_letter
import os
def image_to_excel(image_path, workbook_name, worksheet_name, start_row=1, start_col=1, step_size=10):

    # 加载图片
    img = Image.open(image_path)

    # 创建或打开Excel工作簿
    wb = openpyxl.load_workbook(workbook_name) if os.path.isfile(workbook_name) else openpyxl.Workbook()
    ws = wb[worksheet_name] if worksheet_name in wb.sheetnames else wb.create_sheet(worksheet_name)

    # 获取图片的尺寸
    width, height = img.size

     # 遍历图片，每step_size个像素作为一个单元格处理
    for y in range(0, height, step_size):
        for x in range(0, width, step_size):
            # 截取图片的子区域
            sub_img = img.crop((x, y, min(x + step_size, width), min(y + step_size, height)))

            # 在遍历图片并截取子区域后，计算平均颜色
            pixels = sub_img.getcolors()
            total_pixels = sum(count for count, _ in pixels)
            rgb_values = [sum(color[i] * count for count, color in pixels) for i in range(3)]
            avg_color = tuple(value / total_pixels for value in rgb_values)

            # 在计算平均颜色后，四舍五入并转换为整数
            avg_color_int = tuple(int(round(value)) for value in avg_color)

            # 提取RGB值
            r, g, b = avg_color_int

            # 将颜色转换为openpyxl支持的格式
            color_rgb = Color(rgb=f'FF{r:02X}{g:02X}{b:02X}')

            # 计算对应单元格的位置（确保列索引和行索引始终大于等于1）
            col_idx = start_col + x // step_size
            row_idx = start_row + y // step_size
            cell_address = f'{get_column_letter(max(col_idx, 1))}{max(row_idx, 1)}'

            # 设置单元格的填充色
            ws[cell_address].fill = openpyxl.styles.PatternFill(start_color=color_rgb, end_color=color_rgb, fill_type='solid')
    width = 1
    height = width * (2.2862 / 0.3612)
    for i in range(1, ws.max_row+1):
        ws.row_dimensions[i].height = height
    for i in range(1, ws.max_column+1):
        ws.column_dimensions[get_column_letter(i)].width = width

    # 保存工作簿
    wb.save(workbook_name)

# 使用示例
image_path = '智能法logo.jpg'
workbook_name = '智能法logo.xlsx'
worksheet_name = 'Sheet'
start_row = 1
start_col = 1  # 假设从A1开始
step_size=1
# 确保图片路径有效且文件存在
if os.path.isfile(image_path):
    image_to_excel(image_path, workbook_name, worksheet_name, start_row, start_col,step_size)
else:
    print(f"图片文件 '{image_path}' 不存在，请检查路径是否正确。")
